//1、安装ws模块 npm install ws
//2、导入ws模块
const WebSocket = require("ws");
//3、创建WebSocket服务器

function initSocketServer() {
  const server = new WebSocket.Server({ port: 3001 });
  const _ = require("lodash");
  //4、监听open事件
  server.on("open", () => {
    console.log("建立连接");
  });
  //5、绑定close事件
  server.on("close", () => {
    console.log("关闭连接");
  });
  server.on("listening", function () {
    console.log("ws://localhost:3001 socket服务器启动成功");
  });

  let allUserNum = _.random(10000, 222000);
  let allOrderNum = _.random(10000, 222000);
  //6、绑定connection事件 ws参数表示客户端 req表示客户端的请求信息
  server.on("connection", (ws, req) => {
    //6.1获取客户端的ip port
    const ip = req.connection.remoteAddress;
    const port = req.connection.remotePort;
    const clientName = ip + port;
    console.log("%s is connect", clientName);
    //6.2向客户端发送消息
    setInterval(() => {
      allUserNum += _.random(-500, 1000);
      allOrderNum += _.random(100, 1000);
      let data = {
        code: 1,
        data: {
          allUserNum: allUserNum,
          allOrderNum,
        },
      };
      ws.send(JSON.stringify(data));
    }, 10000);
  });
  // ————————————————
}

module.exports = initSocketServer;
